package controller;

import java.io.IOException;
import java.util.List;

import model.*;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

/**
 * Servlet implementation class SignUpServlet
 */
@WebServlet("/SignUpServlet")
public class SignUpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	
	@PersistenceContext
	EntityManager em;
	
	@Resource
	UserTransaction ut;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignUpServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		ServletContext con = request.getServletContext();
		try{
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String repassword = request.getParameter("repassword");
		
		List<User> users = em.createQuery("select u from User u", User.class).getResultList();
		
		
		if(request.getParameter("signUp")!=null){
			
		for(User temp:users){
			
			if(temp.getUsername().equals(username))
			{
				request.setAttribute("altUser", 1);			
				RequestDispatcher rd = con.getRequestDispatcher("/signUpForm.jsp");
				rd.forward(request, response);
			}
		}
		
		if(password.equals(repassword)){

			
			ut.begin();
			User f = new User();
			f.setUsername(username);
			f.setPassword(password);
			em.persist(f);	
			ut.commit();
			request.setAttribute("accCreated", 1);
			RequestDispatcher rd = con.getRequestDispatcher("/signUpForm.jsp");
			rd.forward(request, response);
		}
		else
		{
			request.setAttribute("wrongPass", 1);
			RequestDispatcher rd = con.getRequestDispatcher("/signUpForm.jsp");
			rd.forward(request, response);
		}}else{
			if(request.getParameter("cancelSignUp")!=null){
				
				RequestDispatcher rd = con.getRequestDispatcher("/loginPage.jsp");
				rd.forward(request, response);
			}
		}
		
		
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
